from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import re
import os
import time

options = Options()
# options.add_argument("--headless")  # 如果不需要界面可以保留此行
user_data_dir = r"C:\Users\Administrator\AppData\Local\Google\Chrome\User Data"
options.add_argument(f"user-data-dir={user_data_dir}")
driver_path = r"F:\宇宙起源推文\chromedriver.exe"  # 确保路径正确
service = Service(driver_path)
driver = webdriver.Chrome(service=service, options=options)


def create_first_page():
	try:
		driver.get("https://kol.fanqieopen.com/page/promotion/list?tab_type=2")
		
		# 显式等待元素加载（最多等20秒）
		WebDriverWait(driver, 600).until(
			EC.presence_of_element_located((By.CLASS_NAME, "book-info-p7GjgI"))
		)
		
		# 提取数据
		books = driver.find_elements(By.CLASS_NAME, "book-info-p7GjgI")
		if books:  # 检查是否有找到书籍
			first_book = books[0]
			title = first_book.find_element(By.CLASS_NAME, "book-name-dAlHLt").text
			extra_info = first_book.find_element(By.CLASS_NAME, "extra-info-_mPyH1").text
			book_id = re.search(r"id: (\d+)", extra_info).group(1)
			print(f"提取成功：{title} | {book_id}")
			return book_id
		else:
			print("未找到任何书籍")
	# 根据需要添加其他操作
	except Exception as e:
		print(f"第一个页面运行错误: {str(e)}")
	

def get_last_file_prefix():
	try:
		directory = r"E:\宇宙起源推文-结果\视频"
		
		# 获取目录下的所有子文件夹
		subfolders = [f.path for f in os.scandir(directory) if f.is_dir()]
		
		if not subfolders:
			print("未找到任何子文件夹")
			return None
		
		# 按名称排序，找到最后一个子文件夹
		last_subfolder = sorted(subfolders)[-1]
		
		# 获取最后一个子文件夹下的所有文件
		files = [f.path for f in os.scandir(last_subfolder) if f.is_file()]
		
		if not files:
			print("最后一个子文件夹中未找到任何文件")
			return None
		
		# 按名称排序，找到最后一个文件
		last_file = sorted(files)[-1]
		
		# 提取文件名的前四位数
		file_name = os.path.basename(last_file)
		if len(file_name) < 4:
			print("文件名长度不足四位")
			return None
		
		first_four_chars = file_name[:4]
		
		return first_four_chars
	
	except Exception as e:
		print(f"运行错误: {str(e)}")
		return None


def read_prefix_file_from_directory(prefix):
	try:
		file_name = "000" + prefix + ".txt"
		# 遍历目录中的所有文件夹
		for root, dirs, files in os.walk('F:\宇宙起源推文\organized_output'):
			for file in files:
				if file == file_name:
					file_path = os.path.join(root, file)
					with open(file_path, 'r', encoding='utf-8') as f:
						content = f.read().strip()
					return content
		
		print("未找到" + prefix + ".txt 文件")
		return None
	
	except Exception as e:
		print(f"读取文件错误: {str(e)}")
		return None


def create_second_page(book_id, content):
	try:
		driver.switch_to.window(driver.window_handles[0])
		
		driver.get("https://kol.fanqieopen.com/page/creator/video")
		
		# 显式等待输入框加载（最多等20秒）
		WebDriverWait(driver, 600).until(
			EC.presence_of_element_located((By.CLASS_NAME, "arco-input"))
		)
		
		input_box = driver.find_element(By.CLASS_NAME, "arco-input")
		input_box.clear()  # 清空输入框（如果需要）
		input_box.send_keys(book_id)
		print(f"已输入 book_id: {book_id}")
		
		# 使用更精确的选择器
		WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//button[contains(@class, 'arco-btn-primary') and contains(span, '开始制作')]"))
		)
		
		# 找到并点击“开始制作”按钮
		button = driver.find_element(By.XPATH, "//button[contains(@class, 'arco-btn-primary') and contains(span, '开始制作')]")
		button.click()
		print("已点击开始制作按钮")
		
		# 等待新标签页打开
		WebDriverWait(driver, 600).until(EC.number_of_windows_to_be(2))
		
		# 切换到新标签页
		driver.switch_to.window(driver.window_handles[1])
		
		# 等待新页面加载完成
		WebDriverWait(driver, 600).until(
			EC.presence_of_element_located((By.CLASS_NAME, "content-input-aMF2yP"))
		)
		
		# 在新页面中进行操作
		# 1. 找到并填写文本区域
		text_area = WebDriverWait(driver, 600).until(
			EC.presence_of_element_located((By.XPATH, "//textarea[@class='arco-textarea']"))
		)
		text_area.send_keys(content)
		print("已填写文本区域")
		
		# 2. 点击“高档”按钮
		high_quality_button = WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable((By.XPATH, "//span[text()='高档']"))
		)
		high_quality_button.click()
		print("已点击高档按钮")
		
		ratio_button = WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable((By.XPATH, "//div[@class='painting-ratio-legend-main-qu40Ko ratio4-3-yumiDE']"))
		)
		ratio_button.click()
		print("已点击4:3比例按钮")
		
		drawclass_button = WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable((By.XPATH, "//div[@class='painting-style-label-k9Vnc9' and text()='梦幻异世']"))
		)
		drawclass_button.click()
		print("已点击梦幻异世比例按钮")
		
		# 4. 点击“生成脚本”按钮
		generate_script_button = WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'generation-button-mkR5_1')]"))
		)
		generate_script_button.click()
		print("已点击生成脚本按钮")
		
		# 5. 点击“生成插画”按钮
		generate_illustration_button = WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//button[contains(@class, 'generation-button-tQap7S') and contains(span, '生成插画')]"))
		)
		print("生成脚本完成")
		generate_illustration_button.click()
		print("已点击生成插画按钮")
		
		# 6. 点击特定的 <canvas> 元素
		canvas_element = WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable((By.XPATH, "//div[@class='painting-tone-label-uVCD_B' and text()='成熟大叔']"))
		)
		print("生成插画完成")
		canvas_element.click()
		print("已点击特定的 <canvas> 元素")
		
		# 7. 点击“合成视频”按钮
		generate_video_button = WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//button[contains(@class, 'arco-btn-primary') and contains(span, '合成视频')]"))
		)
		generate_video_button.click()
		print("已点击合成视频按钮")
		
		# 10. 点击“下载视频”按钮
		download_video_button = WebDriverWait(driver, 600).until(
			EC.element_to_be_clickable(
				(By.XPATH, "//button[contains(@class, 'arco-btn-primary') and contains(span, '下载视频')]"))
		)
		print("合成视频完成")
		download_video_button.click()
		print("已点击下载视频按钮")
		
		download_directory = r"C:\Users\Administrator\Downloads"
		print("开始监控下载目录...")
		initial_count = len([f for f in os.listdir(download_directory) if os.path.isfile(os.path.join(download_directory, f))])
		
		while True:
			time.sleep(15)  # 每15秒检测一次
			current_count = len([f for f in os.listdir(download_directory) if os.path.isfile(os.path.join(download_directory, f))])
			
			if current_count > initial_count:
				print(f"文件数量变化：{initial_count} → {current_count}，下载完成")
				new_files = [f for f in os.listdir(download_directory) if f.startswith("我孙悟空") and os.path.isfile(os.path.join(download_directory, f))]
				if new_files:
					print("检测到目标文件生成")
					break
			print(f"当前文件数 {current_count}，继续监控...")
	# 根据需要添加其他操作
	# 例如，可以在这里添加更多的等待或操作
	
	except Exception as e:
		print(f"第二个页面运行错误: {str(e)}")


def rename_downloaded_file(prefix):
	try:
		download_directory = r"C:\Users\Administrator\Downloads"
		new_name = prefix + "-"
		new_prefix = str(int(prefix) + 1)
		new_file_name = new_name + new_prefix + ".mp4"
		
		# 获取下载目录中的所有文件
		files = [f.path for f in os.scandir(download_directory) if f.is_file()]
		
		if not files:
			print("下载目录中未找到任何文件")
			return
		
		# 找到前几个字符是“我孙悟空”的文件
		for file_path in files:
			file_name = os.path.basename(file_path)
			if file_name.startswith("我孙悟空"):
				new_file_path = os.path.join(download_directory, new_file_name)
				os.rename(file_path, new_file_path)
				print(f"文件已重命名为: {new_file_name}")
				return
		
		print("未找到前几个字符是“我孙悟空”的文件")
	
	except Exception as e:
		print(f"重命名文件错误: {str(e)}")


if __name__ == "__main__":
	# 1、获取book_id
	# 2、获取最新的内容，并填写三遍
	book_id = create_first_page()
	prefix = str(int(get_last_file_prefix()) + 2)
	print(prefix)
	
	for i in range(3):
		oldPrefix = prefix
		content1 = read_prefix_file_from_directory(prefix)
		prefix = str(int(prefix) + 1)
		content2 = read_prefix_file_from_directory(prefix)
		prefix = str(int(prefix) + 1)
		content = content1 + "\n\n" + content2
		
		print(content[:20])
		
		create_second_page(book_id, content)
		driver.close()
		rename_downloaded_file(oldPrefix)
	
	driver.quit()
	